# coding:utf-8
import json
import multiprocessing
import tkinter as tk
import tkinter.messagebox

import ttkbootstrap as tkBoot

from ui.login_message_box import LoginMessageBox
from ui.main_box import MainBox
from util.ui_util import show_center


def newMainBox():
    mainBox = MainBox()
    mainBox.initFrame()


class LoginBox(tkBoot.Window):
    def __init__(self):
        super().__init__(iconphoto="images/icon.png")
        self.username = tk.StringVar()
        self.password = tk.StringVar()
        self.check = tk.BooleanVar()
        self.auto = tk.BooleanVar()
        self.loginBtn = None

    def initFrame(self):
        self.title("登录")
        # self.attributes("-alpha", 0.5)

        # 设置窗口大小和位置
        win_width = int(self.winfo_screenwidth()/3)
        win_height = int(self.winfo_screenheight()/3)
        show_center(self, win_width, win_height)
        self.resizable(False, False)

        # 创建内部框体
        frame = tkBoot.Frame(self)
        frame.pack(fill=tk.Y, expand=True, pady=80)

        # 创建标签和输入框
        userRow = tk.Frame(frame)
        tkBoot.Label(userRow, width=5, text="账号").pack(side=tk.LEFT)
        tkBoot.Entry(userRow, width=25, textvariable=self.username).pack(side=tk.RIGHT)
        userRow.pack(pady=(0, 15))
        pswRow = tk.Frame(frame)
        tkBoot.Label(pswRow, width=5, text="密码").pack(side=tk.LEFT)
        tkBoot.Entry(pswRow, width=25, show="*", textvariable=self.password).pack(side=tk.RIGHT)
        pswRow.pack(pady=(0, 15))

        # 创建复选框和按钮
        settingsRow = tk.Frame(frame)
        tkBoot.Checkbutton(settingsRow, text="记住账号", variable=self.check, onvalue=True, offvalue=False).pack(side=tk.LEFT, padx=(0, 15))
        tkBoot.Checkbutton(settingsRow, text="自动登录", variable=self.auto, onvalue=True, offvalue=False).pack(side=tk.RIGHT, padx=(15, 0))
        settingsRow.pack(pady=(0, 15))

        loginBtn = tkBoot.Button(frame, width=30, text="登录", command=self.fireLogin)
        loginBtn.pack()
        self.loginBtn = loginBtn

        self.after(500, self.auto_login)
        self.mainloop()

    def auto_login(self):
        if len(self.username.get().strip()) > 0 and len(self.password.get().strip()) > 0 and self.auto.get():
            self.loginBtn.invoke()

    def fireLogin(self) -> None:
        if self.loginSuccess():
            loginMessageBox = LoginMessageBox(self)
            loginMessageBox.initFrame()

    def doLogin(self) -> None:
        if self.loginSuccess():
            self.saveUiSetting()
            self.destroy()
            multiprocessing.Process(target=newMainBox).start()

    def loginSuccess(self) -> bool:
        if self.username.get() == "admin" and self.password.get() == "123456":
            return True
        if self.username.get() == "" or self.password.get() == "":
            tk.messagebox.showinfo(title="提示", message="请输入用户名密码")
        else:
            tk.messagebox.showinfo(title="错误", message="用户名密码错误")
        return False

    def saveUiSetting(self):
        uiSettingJson = {
            "check": self.check.get(),
            "auto": self.auto.get()
        }
        with open("resource/data.json", "w") as f:
            if self.check:
                uiSettingJson["username"] = self.username.get()
                uiSettingJson["password"] = self.password.get()
            json.dump(uiSettingJson, f)

    def loadUiSetting(self):
        with open("resource/data.json", "r") as f:
            uiSettingJson = json.load(f)
            self.check.set(uiSettingJson["check"])
            self.auto.set(uiSettingJson["auto"])
            if uiSettingJson["check"]:
                self.username.set(uiSettingJson["username"])
                self.password.set(uiSettingJson["password"])
